#!/usr/bin/env python
#-*- encoding=utf8-*-
import settings,sys,re


def get_file_datestr(full_file_name):
    """
    get s_cyc_date from file_name.
    """
    pattern = re.compile(settings.DATE_PATTERN)
    date_re = re.search(pattern,full_file_name)
    if date_re:
        date_str = date_re.group()
    else:
        date_str = ''
    return date_str


def get_legal_load_file(src_filename):
    """
    confirm legal files.
    """
    file_timestr = get_file_datestr(src_filename)
    if file_timestr:
        if file_timestr.strip()[-1] in ['0','5']:
            return True
        else:
            return False
    else:
        return False


def get_file_namestr(full_file_name):
    """
    get s_cyc_date from file_name.
    """
    pattern = re.compile(settings.FILE_PATTERN)
    filename_re = re.search(pattern,full_file_name)
    if filename_re:
        filename_str = filename_re.group()
    else:
        filename_str = ''
    return filename_str


def read_process_write(file_name):
    """
    read and process,then write to load_dir
    """

    #get s_cycle_date.
    s_cycle_date = get_file_datestr(file_name)
    if s_cycle_date == '':
        print 's_cycle_date is null!'
        sys.exit(1)

    #read and add s_cycle_date column.
    lines_str = ''
    with open(file_name,'r') as fp:
        for line in fp:
            lines_str += line.strip() + settings.FIELDS_SEPARATOR + s_cycle_date + '\n'

    #write to anther directory: load_dir
    loadfile_name = settings.LOAD_DIR + s_cycle_date + settings.FILE_SUFFIX
    with open(loadfile_name,'w') as wp:
        wp.write(lines_str)

    return loadfile_name
